import subprocess


def install_docker(commands):
    try:
        # 执行安装必要软件包的命令
        subprocess.run(commands['install_command'], check=True, shell=True)

        # 执行添加 Docker 的官方 GPG 密钥的命令
        subprocess.run(commands['gpg_command'], check=True, shell=True)

        # 执行设置 Docker 仓库的命令
        subprocess.run(commands['docker_repo_command'], check=True, shell=True)

        # 执行更新软件包索引的命令
        subprocess.run(commands['update_command'], check=True, shell=True)

        # 执行安装 Docker CE 的命令
        subprocess.run(commands['docker_install_command'], check=True, shell=True)

        # 执行安装 docker-compose 的命令
        subprocess.run(commands['docker_compose_install_command'], check=True, shell=True)
        subprocess.run(commands['docker_compose_chmod_command'], check=True, shell=True)

        print("Docker 和 docker-compose 已成功安装。")
    except subprocess.CalledProcessError as e:
        print(f"在安装 Docker 过程中发生错误：{e}")


# 定义命令字典
commands = {
    'install_command': "apt-get install apt-transport-https ca-certificates curl software-properties-common -y",
    'gpg_command': "curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg",
    'docker_repo_command': "echo 'deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable' | tee /etc/apt/sources.list.d/docker.list",
    'update_command': "apt-get update -y",
    'docker_install_command': "apt-get install docker-ce=5:25.0.5-1~ubuntu.22.04~jammy -y",
    'docker_compose_install_command': "curl -L https://github.com/docker/compose/releases/download/v2.2.3/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose",
    'docker_compose_chmod_command': "chmod +x /usr/local/bin/docker-compose"
}

# 调用安装函数
install_docker(commands)